﻿using Microsoft.AspNetCore.Authorization;
using PlayingCards.Comm.Extensions;
using PlayingCards.Model.Entity;
using PlayingCards.Model.Result;
using PlayingCards.Repository.BaseRepository;
using PlayingCards.Service.IEntityService;
using PlayingCards.Service.TokenService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace PlayingCards.Service.EntityService
{
    /// <summary>
    ///  房间实现类
    /// </summary>
    public class RoomService : IRoomService
    {
        private readonly BaseRepository<Room> _room;
        private readonly BaseRepository<PlayerList> _playerlist;
        private readonly IUserTokenService _userTokenService;

        public RoomService(BaseRepository<Room> room, BaseRepository<PlayerList> playerlist, IUserTokenService userTokenService)
        {
            _room = room;
            _playerlist = playerlist;
            _userTokenService = userTokenService;
        }

        /// <summary>
        ///  创建房间
        /// </summary>
        /// <param name="roomcode"></param>
        /// <returns></returns>
        public async Task<Result<string>> CreateRoom(string roomcode)
        {
            var name = await _userTokenService.GetUser();
            var roomid = await _room.InsertReturnIdentityAsync(new Room()
            {
                RoomNumber = "R" + DateTimeExtension.GenerateNumberString(),
                PlayerNumber = name.Id,
                Name = name.NickName + "的房间",
                RoomState = 0,
                RoomCode = roomcode,
                GameDuration = DateTime.Now

            });
            await _playerlist.InsertAsync(new PlayerList()
            {
                PlayerId = name.Id,
                RoomId = roomid

            });
            return new Result<string> { Status = true, Message = "创建成功" };
        }

        /// <summary>
        ///  查询房间
        /// </summary>
        /// <param name="RoomNumber"></param>
        /// <returns></returns>
        public async Task<Result<string>> GetRoom(string RoomNumber)
        {
            var room = await _room.GetFirstAsync(e => e.RoomNumber == RoomNumber);
            return new Result<string> { Data = room.RoomNumber };
        }

        /// <summary>
        ///  进入房间
        /// </summary>
        /// <param name="roomcode">房间码</param>
        /// <returns></returns>
        public async Task<Result<Room>> JoinRoom(string roomcode)
        {
            var model = await _room.GetFirstAsync(e => e.RoomCode == roomcode);
            if (model == null) return new Result<Room> { Status = false, Message = "房间码错误" };

            var playerId = await _userTokenService.GetUserId();
            await _playerlist.InsertAsync(new PlayerList(){ RoomId = model.Id, PlayerId = playerId });

            return new Result<Room> { Data = model};
        }
    }
}
